package member

import (
	"awfan.cn/utils"

	"strings"

	"net/http"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

func auth(format, name, password, school string, w http.ResponseWriter, db *mgo.Database) {
	if name == "" {
		utils.WriteError(format, 404, "#name is empty", w)
		return
	}

	if password == "" {
		utils.WriteError(format, 404, "#password is empty", w)
		return
	}
	if school == "" {
		utils.WriteError(format, 404, "#school is empty", w)
		return
	}

	var data = MEMBER_XML{}

	c := db.C(utils.PkgName(MEMBER_XML{}))

	q := c.Find(bson.M{
		"name":      bson.RegEx{"^" + name + "$", "i"},
		"school.id": school,
		"$or": []bson.M{
			bson.M{"password": bson.RegEx{"^" + password + "$", "i"}},
			bson.M{"token": bson.RegEx{"^" + password + "$", "i"}},
		},
	})

	var count int
	var err error

	if count, err = q.Count(); err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}

	if count <= 0 {
		utils.WriteError(format, 402, "#name not exist", w)
		return
	}

	if err := q.One(&data); err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}

	data.Token = utils.RandString(32)

	token := strings.ToUpper(utils.HexMD5(data.Token))

	if err := c.UpdateId(data.Id, bson.M{"$set": bson.M{"token": token}}); err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}
	var url string
	if url, err = utils.ToImageFile(data.Id.Hex(), data.Image); err != nil {
		utils.WriteError(format, 404, err.Error(), w)
		return
	}

	data.Image = url

	utils.WriteData(format, data, w)
}
